/*
 * Eugen Stoian <stoian.e@gmail.com> 2010
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <QtCore/QByteArray>
#include <QtCore/QDir>
#include <QtCore/QLibraryInfo>
#include <QtCore/QProcess>

#include <QtGui/QMessageBox>
#include "HelpAssistant.h"

HelpAssistant::HelpAssistant()
 : proc(0){
}

HelpAssistant::~HelpAssistant()
{
 if (proc && proc->state() == QProcess::Running) {
     proc->terminate();
     proc->waitForFinished(3000);
 }
 delete proc;
}

void HelpAssistant::showDocumentation(const QString& page)
{
 if (!startAssistant())
     return;

 QByteArray ba("SetSource ");

 proc->write(page.toLocal8Bit() + '\0');
}

bool HelpAssistant::startAssistant()
{
 if (!proc)
     proc = new QProcess();

 if (proc->state() != QProcess::Running) {
     QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator();
     app += QLatin1String("assistant");

     QStringList args;
     args << QLatin1String("-collectionFile")
         << QLatin1String("qbernoulli.qhc")
         << QLatin1String("-enableRemoteControl");

     proc->start(app, args);

     if (!proc->waitForStarted()) {
         QMessageBox::critical(0, QObject::tr("Simple Text Viewer"),
             QObject::tr("Unable to launch Qt HelpAssistant (%1)").arg(app));
         return false;
     }
 }
 return true;
}
